package com.shop.shop_end.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.shop_end.entity.MessageJson;
import com.shop.shop_end.mapper.MessageJsonMapper;
import com.shop.shop_end.mapper.UserMapper;
import com.shop.shop_end.service.MessageJsonService;
import com.shop.shop_end.utils.redis.RedisCache;
import com.shop.shop_end.utils.result.Result;
import com.shop.shop_end.utils.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MessageJsonServiceImpl implements MessageJsonService {
    final Logger logger = LoggerFactory.getLogger(MessageJsonServiceImpl.class);

    @Resource
    private MessageJsonMapper messageJsonMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisCache redisCache;

    /**
     * 增加一条消息
     * @param messageJson
     * @return
     */
    @Override
    public Result addOneMsg(MessageJson messageJson) {
        log.info("{}发了一条信息。", messageJson.getUsername());
        //1、先存redis
        //1-1、取出现有的消息数据
        String key = "messageList" + "_" + messageJson.getCeId();//生成key
        List<MessageJson> messageJsonList = redisCache.getCacheList(key);
        //1-2、拼接
        messageJsonList.add(messageJson);//将刚发的消息拼接到已有的消息尾部
        //1-3、删除redis中的消息数据
        redisCache.deleteObject(key);
        //1-4、放入新的消息数据
        redisCache.setCacheList(key, messageJsonList);//存redis
        return ResultUtil.ok(messageJson);
    }

    /**
     * 获取消息
     * @param sendId
     * @param receiveId
     * @return
     */
    @Override
    public Result getMyMsg(Long sendId, Long receiveId) {//可能会有问题
        List<MessageJson> messageJsonList = new ArrayList<>();//汇总
        //1、从数据库里获取消息
        QueryWrapper<MessageJson> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", sendId).eq("mid", receiveId)//我发的消息
                .or()
                .eq("uid", receiveId).eq("mid", sendId)//对方发的消息
                .orderByAsc("currentTime");//按照时间升序
        List<MessageJson> messageJsonList1 = messageJsonMapper.selectList(wrapper);
        //2、获取ceId
        String ceId1 = String.valueOf(userMapper.selectById(sendId).getUserId());//我的ceId
        String ceId2 = String.valueOf(userMapper.selectById(receiveId).getUserId());//对方的ceId
        //3、从redis里获取消息
        String key1 = "messageList" + "_" + ceId1;//生成key1
        String key2 = "messageList" + "_" + ceId2;//生成key2
        Set<String> keys = redisCache.getKeysByPattern("*"+"messageList"+"*");//查询所有key
        if (keys.size() != 0){//Redis里是否有消息数据
            if (keys.contains(key1)){//包含key1的话就查询其value
                List<MessageJson> messageJsonList2 = redisCache.getCacheList(key1);//我发的消息
                //挑选出数据，筛选出mid是当前对方的
                messageJsonList2 = messageJsonList2.stream().filter((item)->
                        item.getMid() == receiveId).collect(Collectors.toList());
                messageJsonList.addAll(messageJsonList2);
            }
            if (keys.contains(key2)){//包含key1的话就查询其value
                List<MessageJson> messageJsonList3 = redisCache.getCacheList(key2);//对方发的消息
                messageJsonList3 = messageJsonList3.stream().filter((item)->
                        item.getMid() == sendId).collect(Collectors.toList());
                messageJsonList.addAll(messageJsonList3);
            }
        }
        messageJsonList.addAll(messageJsonList1);//再添加数据库里查询到的数据
        return ResultUtil.ok(messageJsonList);
    }


    /**
     * 删除一条消息，用于撤回
     * @param messageJson
     * @return
     */
    @Override
    public Result delOneMsg(MessageJson messageJson) {
        return null;
    }

    /**
     * 批量删除数据
     * @param messageJson
     * @return
     */
    @Override
    public Result delPartMsg(MessageJson messageJson) {
        return null;
    }
}
